/**
 * @author hugan
 * @date 2023/10/4
 */
import "../common/plugins/vue/2.6.11.min.js"
import "../component/HTouchpad.js"
import "../component/HKeyboard.js"
import env from "../common/env.js"
import storageUtil from "../common/util/storageUtil.js";
import websocketUtil from "../common/util/websocketUtil.js";
import browserUtil from "../common/util/browserUtil.js"

{
  new Vue({
    el: '#app',
    data() {
      return {
        wsStatus: '未连接',
        websocket: null,
        //要发送的文本
        inputText: '',
        showKeyboard: false,
      }
    },
    watch: {
      wsStatus(newValue) {
        document.title = newValue
        this.$refs.hKeyboard.onWsStatusChanged(this.websocket.readyState)
      }
    },
    mounted() {
      // console.log('mounted')
      let token = storageUtil.getString('tk', '')
      if (!token) {
        window.location.href = './login.html'
        return
      }
      //
      this.initWebsocket(token)
      this.initButton()

      //监听[全屏切换]
      window.addEventListener('resize', () => {
        // console.log('resize', window.innerWidth, window.innerHeight, browserUtil.isFullScreen())
        this.showKeyboard = browserUtil.isFullScreen()
        if (this.showKeyboard) {
          this.$refs['hKeyboard'].reloadConfig()
          this.getKeyboardState()
        } else {
          this.$refs['touchpadBig'].reloadConfig()
        }
      })
    },
    methods: {
      initWebsocket(token) {
        this.wsStatus = '连接中'
        let websocket = new WebSocket(env.wsBaseUrl() + `/ws`)
        websocket.binaryType = "arraybuffer"
        this.websocket = websocket
        //窗口关闭时，主动关闭websocket
        window.onbeforeunload = () => websocket.close()

        websocket.onopen = () => {
          console.log("连接成功")
          this.wsStatus = '已连接'
          websocketUtil.send(this.websocket, 'wsLogin', {token})
        }
        websocket.onclose = (event) => {
          console.log("连接关闭")
          this.wsStatus = '未连接'
        }
        websocket.onerror = (event) => {
          console.log("连接错误")

        }
        websocket.onmessage = (event) => {
          // console.log("收到消息", event)
          websocketUtil.handleMessage(event, this)
        }
      },
      //ws(收发)消息.st=====
      onTouchpadEvent(event, data) {
        // console.log('onTouchpadEvent', event, data)
        if ('down' === event) {
          // 移动端.收起键盘: 需要被触摸的div有tabindex属性
          this.$refs.txtInput.blur()
        }
        if ('mouseButton' === event) {
          this.$refs.txtInput.blur()
          websocketUtil.send(this.websocket, 'buttonAction', data)
        } else {
          websocketUtil.send(this.websocket, 'mouseAction', data)
        }
      },
      onScrollEvent(data) {
        websocketUtil.send(this.websocket, 'scrollAction', data)
      },
      getKeyboardState() {
        websocketUtil.send(this.websocket, 'getKeyboardState')
      },
      onKeyboardState(state) {
        // console.log('onKeyboardState', state)
        this.$refs['hKeyboard'].onKeyboardState(state)
      },
      //ws消息.ed=====
      /**
       * 初始化按钮监听
       */
      initButton() {
        /*
        keyCode 来自
        键盘: java.awt.event.KeyEvent.VK_F1
        鼠标: MockActionService.MouseButton
         */
        let addListener = button => {
          if (button.getAttribute('keyCode')) {
            // console.log('button', button.innerHTML)
            button.addEventListener('touchstart', e => {
              // console.log('touchstart', e.target.innerText, e, e.target.classList)
              e.target.classList.add('activeButton')//手工添加class,支持同时按下多个按键
              websocketUtil.send(this.websocket, 'buttonAction', this.buildButtonAction(e.target, 1))
              if (button.hasAttribute('updateKeyboardState')) this.getKeyboardState()
              if (e.cancelable) e.preventDefault() //调用后会丢失[按下按钮的ui效果]
            })
            button.addEventListener('touchend', e => {
              // console.log('touchend', e.target.innerText, e)
              e.target.classList.remove('activeButton')
              websocketUtil.send(this.websocket, 'buttonAction', this.buildButtonAction(e.target, 2))
              if (button.hasAttribute('updateKeyboardState')) this.getKeyboardState()
              if (e.cancelable) e.preventDefault()
            })
            button.addEventListener('click', e => {
              if (e.pointerType === 'touch') return//过滤触摸事件触发的重复事件
              // console.log('click', e.target.innerText, e.pointerType, e)
              websocketUtil.send(this.websocket, 'buttonAction', this.buildButtonAction(e.target, 3))
              if (button.hasAttribute('updateKeyboardState')) this.getKeyboardState()
            })
          } else {
            // console.log('未知按钮', button.innerText)
          }
        }
        //全部button, 键盘灯
        for (let button of document.querySelectorAll('button, .lamp-row span')) {
          addListener(button)
        }
      },
      buildButtonAction(button, action) {
        let res = {action}
        res.keyCode = button.getAttribute('keyCode')
        res.type = button.getAttribute('isMouse') ? 2 : 1
        //console.log('keyCode=', button.innerHTML, button.getAttribute('keyCode'))
        return res
      },
      toFullScreen() {
        browserUtil.toFullScreen()
      },
    },
  })
}